package org.naive.vstream;

import java.io.IOException;
import java.io.OutputStream;

public class ReconstructionPlan {
	private final OutputStream output;

	private int currentByte;

	private int bitIndex;

	public ReconstructionPlan(OutputStream output) {
		super();
		this.output = output;
	}

	public void open() throws IOException {
		write(true);
	}

	public void skip() throws IOException {
		write(false);
	}

	public void brightness(int value) throws IOException {
		if (value >= 16) {
			write(true);
			write(true);
			write(true);
			write(true);
		}
		else {
			for (int i = 0; i < 4; i++) {
				write((value & 0x1) != 0);
				value >>>= 1;
			}
		}
	}

	private void write(boolean bit) throws IOException {
		currentByte |= (bit ? 0b100000000 : 0b0);
		currentByte >>>= 1;

		if (++bitIndex >= 8) {
			bitIndex = 0;
			output.write(currentByte);
			currentByte = 0;
		}
	}

	public void close() throws IOException {
		while (bitIndex > 0) {
			write(false);
		}
		output.close();
	}
}
